package util;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import easydst.Machine;

public class Utilities {

	// TODO verificar se o arquivo existe
	public static List<String> getMachinesFromFile(String fileName) {

		List<String> machines = new ArrayList<String>();
		try {
			BufferedReader in = new BufferedReader(new FileReader(fileName));

			String oneMachine;
			while (in.ready()) {
				oneMachine = in.readLine();
				machines.add(oneMachine);
			}
			in.close();
		} catch (IOException e) {
		}
		return machines;
	}

	public static void createAgentsIntoMachine(Machine machine) {
		Msg.log("Creating test agent into machine: " + machine.getHostname());
		
//		String filePath = "/home/giovanni/Desktop/Survey.rar"; TODO
		String filePath = "../../scripts/createTestAgent.sh";
		
		File file = new File(filePath);
		String remoteFilePath = (new File("/local/giovanni/", file.getName())).getAbsolutePath();
		
		try {
			System.out.println("Antes de chamar o SCP!!");//TODO
			Scp.to(machine.getHostname()).copy(filePath, remoteFilePath);
			System.out.println("Depois de chamar o SCP!!");//TODO
			
		} catch (IOException e) {
			System.err.println("Deu erro!!");
			e.printStackTrace();
		}
		
		try {
			//ssh(machine, "rmiregistry", "&");
			ssh(machine, "chmod +x " + remoteFilePath);
			ssh(machine, remoteFilePath + " &");
		} catch (Exception e) {
			Msg.error("");
			e.printStackTrace();
		}			
	}

	
	private static void ssh(Machine machine, String command, Object... args) throws Exception {
		System.out.println("Comando: " + command);//TODO
		System.out.println("Args: " + args);//TODO
				
		Ssh.Result result = Ssh.to(machine.getHostname()).exec(command, args);
		System.out.println("Resultado: "); //TODO
		System.out.println("Exit Status: " + result.getProcessExitStatus());//TODO
		System.out.println("Output: " + result.getOutput());//TODO
		if (result.getProcessExitStatus() != 0) {
			throw new RuntimeException(result.getOutput());
		}
	}
}
